import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Message, TemplateService } from 'src/app/common/providers';
import { EditComponent } from '../edit/edit.component';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.less'],
})
export class ListComponent implements OnInit {
  // 编辑对话框的子视图
  @ViewChild('edit') edit: EditComponent;
  // 搜索栏响应式表单
  searchForm: FormGroup;
  // 搜索按钮加载状态
  hasClicked = false;
  // 表格数据
  messageData: Message[] = [];
  // 控制表格加载状态
  isLoading = false;
  // 表格数据总数
  total = 0;
  // 表格分页大小
  pageSize = 10;
  // 表格当前页
  pageIndex = 1;

  constructor(
    private fb: FormBuilder,
    private templateServ: TemplateService,
    private modal: NzModalService
  ) {
    this.searchForm = this.fb.group({
      name: [''],
      type: [''],
    });
  }

  ngOnInit(): void {
    this.loadData(1);
  }

  /**
   * 加载表格数据
   * @param index 分页数据页码
   */
  loadData(index = 1): void {
    this.isLoading = true;
    this.templateServ
      .getMessageList({
        pageIndex: index,
        pageSize: this.pageSize,
        searchOption: this.searchForm.value,
      })
      .subscribe({
        next: (res) => {
          if (res.success) {
            this.messageData = res.data;
            this.pageIndex = res.pageIndex;
            this.total = res.total;
          }
        },
        complete: () => {
          this.isLoading = false;
        },
      });
  }

  /**
   * 新增或修改消息数据
   * @param data 消息数据，新增时此数据为空
   */
  editData(data?: any): void {
    this.edit.show(data);
  }

  /**
   * 根据 ID 删除消息数据
   * @param id 消息数据 ID
   */
  deleteData(id: number): void {
    // 显示确认是否删除
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认删除？',
      nzOnOk: () => {
        this.templateServ.deleteMessage(id).subscribe((res) => {
          if (res.success) {
            // 删除成功
            this.loadData(this.pageIndex);
          }
        });
      },
    });
  }

  /**
   * 监听编辑框组件提交事件
   * @param status 提交事件返回参数，create / update
   */
  onEditSubmit(status: string): void {
    if (status === 'update') {
      // 修改数据
      this.loadData(this.pageIndex);
    } else if (status === 'create') {
      // 新增数据
      this.loadData();
    }
  }
}
